package com.zhenhao.xsq.application;

import android.app.Application;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.graphics.Color;
import android.os.Build;

import com.blankj.utilcode.util.DeviceUtils;
import com.orhanobut.logger.AndroidLogAdapter;
import com.orhanobut.logger.Logger;
import com.orhanobut.logger.PrettyFormatStrategy;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreator;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreator;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.zhenhao.xsq.BuildConfig;
import com.zhenhao.xsq.contain.Contains;
import com.zhenhao.xsq.data.api.support.LogCatStrategy;
import com.zhenhao.xsq.db.green.DaoMaster;
import com.zhenhao.xsq.db.green.DaoSession;
import com.zhenhao.xsq.utils.SpUtil;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

import androidx.multidex.MultiDex;
import me.jessyan.autosize.AutoSizeConfig;

public class AppConfig  extends Application {

    /**
     * 为了实现每次使用该类时不创建新的对象而创建的静�?对象
     */
    public static AppConfig instance;
    private AppComponent mAppComponent;
    //公共安防
    public static String AppKey = "13edae3069574e6bad0c49474b9344da";//萤石云初始化 公共监控
    public static String AppSecret = "8b2ee852dadd753b8138494800b4afe7";

    public AppConfig() {

    }

    public static synchronized AppConfig getInstance() {
        if (null == instance) {
            instance = new AppConfig();
        }
        return instance;
    }

    //static 代码段可以防止内存泄露
    static {
        //设置全局的Header构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
            @Override
            public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
//                layout.setPrimaryColorsId(R.color.colorPrimary, android.R.color.white);//全局设置主题颜色
                return new ClassicsHeader(context);//.setTimeFormat(new DynamicTimeFormat("更新于
                // %s"));//指定为经典Header，默认是 贝塞尔雷达Header
            }
        });
        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
            @Override
            public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
                //指定为经典Footer，默认是 BallPulseFooter
                return new ClassicsFooter(context);
//                return new ClassicsFooter(context).setDrawableSize(20);
            }
        });

    }

    @Override
    public void onCreate() {
        super.onCreate();
        setupApplicationComponent();
        instance = this;

        //适配
        initAutoSize();
        PrettyFormatStrategy strategy = PrettyFormatStrategy.newBuilder().logStrategy(new
                LogCatStrategy()).tag("LOG_TAG").build();
        //也可以写成下面的这样，来控制日志是否打印
        Logger.addLogAdapter(new AndroidLogAdapter(strategy) {
            @Override
            public boolean isLoggable(int priority, String tag) {
                return BuildConfig.DEBUG;//(控制日志是否打印)
            }
        });

        String manufacturer = DeviceUtils.getManufacturer();
        int sdkVersionCode = DeviceUtils.getSDKVersionCode();
//        Log.e("wh", "manufacturer " + manufacturer);

        int anInt = SpUtil.getInt(this, Contains.SP_APP_PRIVATE, 0);
        // 获取隐私政策签署状态
        boolean sign = false;
        if (anInt == 0) {
            sign = false;
        } else {
            sign = true;
        }

//        String sdkVersionName = DeviceUtils.getSDKVersionName();
//        Log.e(TAG + " wh", "sdkVersionName " + sdkVersionName + " sdkVersionCode " + sdkVersionCode);
        if (sdkVersionCode >= 28) {
            closeAndroidPDialog();
        }

    }

    /**
     * 适配Android 28 对使用非 SDK API 弹窗处理
     */
    private void closeAndroidPDialog() {
        try {
            Class aClass = Class.forName("android.content.pm.PackageParser$Package");
            Constructor declaredConstructor = aClass.getDeclaredConstructor(String.class);
            declaredConstructor.setAccessible(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            Class cls = Class.forName("android.app.ActivityThread");
            Method declaredMethod = cls.getDeclaredMethod("currentActivityThread");
            declaredMethod.setAccessible(true);
            Object activityThread = declaredMethod.invoke(null);
            Field mHiddenApiWarningShown = cls.getDeclaredField("mHiddenApiWarningShown");
            mHiddenApiWarningShown.setAccessible(true);
            mHiddenApiWarningShown.setBoolean(activityThread, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);

        MultiDex.install(this);////突破65535限制
    }

    protected void setupApplicationComponent() {
        mAppComponent = DaggerAppComponent.builder()
                .appModule(new AppModule(this))
                .aPIModule(new APIModule(this))
                .build();
        mAppComponent.inject(this);
    }

    public AppComponent getApplicationComponent() {
        return mAppComponent;
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        System.gc();
    }

    private void initAutoSize() {
        AutoSizeConfig.getInstance()
                .setDesignWidthInDp(375)  //设置设计图的宽度，单位dp
                .setDesignHeightInDp(667) //设置设计图的高度，单位dp
                .setExcludeFontScale(false) //是否排除系统字体的影响
//                .setUseDeviceSize(false)  //是否使用机型自带的字体配置
                .setLog(BuildConfig.DEBUG) //是否打印日志
//                .setCustomFragment(true) //是否支持自定义适配Fragment
//                .setUnit(UnitsManager.SUB_UNIT_DP)//设置单位，这里使用dp作为基准单位
        ;
    }

    static DaoSession mDaoSessin;

    public static DaoSession getGreenDaoSession() {
        if (mDaoSessin == null) {
            DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(instance, "user-db", null);
            DaoMaster daoMaster = new DaoMaster(devOpenHelper.getWritableDatabase());
            mDaoSessin = daoMaster.newSession();
        }
        return mDaoSessin;
    }

}
